package cc.momas.momall.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cc.momas.common.utils.JsonUtils;

/**
 * 图片上传控制器
 * @author sod
 *
 */
@Controller
public class PictureController {

	//图片服务器地址,从spring mvc中读取
	@Value("${IMAGE_SERVER_URL}")
	private String IMAGE_SERVER_URL;
	//图片在服务器的地址
	private String IMAGE_LOCATION = "/upload/itemdesc/";
	
	
	/**
	 * TEXT_PLAIN_VALUE指定了使用"text/plain"头类型,这样可以避免浏览器对JSON解析兼容性
	 * @param request
	 * @param uploadFile
	 * @return
	 */
	@RequestMapping(value="/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE + ";charset=utf-8")
	@ResponseBody
	public String uploadFile(HttpServletRequest request,MultipartFile uploadFile,String dir) {
		
		String targetDir = request.getSession().getServletContext().getRealPath(IMAGE_LOCATION);
		System.err.println("图片服务器地址:" + targetDir);//测试地址
		String originalFileName = uploadFile.getOriginalFilename();
		String extName = originalFileName.substring(originalFileName.lastIndexOf("."));
		String newFilename = UUID.randomUUID().toString() + extName;//使用UUID生成新文件名
		File newFile = new File(targetDir,newFilename);

		Map<String,Object> result = null;
		try {
			//将上传的文件写入新文件
			uploadFile.transferTo(newFile);
			//补充完整的URL
			String url = IMAGE_SERVER_URL + newFilename;
			//封装到MAP中返回
			result = new HashMap<>();
			result.put("error", 0);
			result.put("url",url);
		} catch (IllegalStateException | IOException e) {
			result.put("error", 1);
			result.put("message", "图片上传失败,大概原因:" + e.getMessage());
			e.printStackTrace();
		}
		
		return JsonUtils.objectToJson(result);
	}


}



